/**    
d * 文件名：DdLockRest.java</br>
 *    
 * 版本信息：v1.0</br>
 * 日期：2017年6月26日</br>
 * © 2005-2017 雷技信息科技（上海）有限公司版权所有</br>
 *
 */
package com.logic.landseaserver.ws;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.landseaserver.common.LandeaConstants.DdingConstant;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.LoggerHelper;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.DdingEventCallbackEvt;
import com.logic.landseaserver.domain.DdingModPwdLog;
import com.logic.landseaserver.domain.DdingProjectConfig;
import com.logic.landseaserver.domain.DdingPwdCallbackEvt;
import com.logic.landseaserver.service.IDdLockService;
import com.logic.landseaserver.service.impl.SendByRoomService;
import com.logic.landseaserver.ws.request.SendAddPwdByRoomReq;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 * 
 * 项目名称：system-server</br>
 * 类名称：DdLockRest</br>
 * 类描述：朗诗对接云丁门锁控制器</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年6月26日 下午4:16:38</br>
 * 
 * @version 1.0
 *
 */
@Path("/ddlock")
@Api(value = "ddlock")
public class DdLockRest
{
    private static final Logger LOG = LoggerFactory.getLogger(DdLockRest.class);
    
    @Autowired
    private IDdLockService ddLockService;
    @Autowired
    private SendByRoomService sendByRoomService;
    
    /**
     * 
     * [简要描述]：同步项目及项目内房间至云丁系统</br>
     * [详细描述]：本接口耗时可能很大，前端应做异步</br>
     * [作者]：Aaron(2017-06-26)</br>
     *
     * @param projectId 项目ID
     * @return 结果
     *
     */
    @POST
    @Path("/syncHomeAndRooms")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "synchronize project and rooms to yunding system.")
    public Response syncHomeAndRooms(@ApiParam(value = "project_id", required = true) int projectId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            ddLockService.syncHomeAndRooms(projectId);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "syncHomeAndRooms", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：保存项目配置项</br>
     * [详细描述]：不存在走新增，存在走更新</br>
     * [作者]：Aaron(2017-06-26)</br>
     *
     * @param projectConfigArray 云丁项目配置数组
     * @return 结果
     *
     */
    @POST
    @Path("/saveProjectConfigs")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "add or update project configs.")
    public Response saveProjectConfigs(
        @ApiParam(value = "param", required = true) DdingProjectConfig[] projectConfigArray)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            int result = ddLockService.saveDdingProjectConfig(projectConfigArray);
            map.setData(result);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "saveProjectConfigs", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：保存项目配置项</br>
     * [详细描述]：不存在走新增，存在走更新</br>
     * [作者]：Aaron(2017-06-26)</br>
     *
     * @param projectId 云丁项目配置数组
     * @return 结果
     *
     */
    @POST
    @Path("/getProjectConfigs")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "get project configs.")
    public Response getProjectConfigs(@ApiParam(value = "projectId", required = true) Integer projectId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            List<DdingProjectConfig> result = ddLockService.getDdingProjectConfig(projectId);
            map.setData(result);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "getProjectConfigs", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：获取项目房间同步情况及安装锁情况</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-06-30)</br>
     *
     * @param projectId 云丁项目配置数组
     * @return 结果
     *
     */
    @POST
    @Path("/ddingProjectRoomStatistic")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Statistic synchronous rooms and install lock romms.")
    public Response ddingProjectRoomStatistic(@ApiParam(value = "projectId", required = true) Integer projectId)
    {
        CommonResultMap map = new CommonResultMap();
        // 异步接口，不抛出异常
        Map<String, Object> result = ddLockService.ddingProjectRoomStatistic(projectId);
        map.setData(result);
        map.setResult(CommonResult.SUCCESS);
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：修改门锁密码，通知云丁修改密码</br>
     * [详细描述]：异步接口，云丁修改成功与否会回调另外的本地接口</br>
     * [作者]：Aaron(2017-06-30)</br>
     *
     * @param roomId 房间Id
     * @return 结果
     *
     */
    @POST
    @Path("/modifyDoorPassword")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "modify room door password.")
    public Response modifyDoorPassword(@ApiParam(value = "roomId", required = true) Integer roomId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            ddLockService.modifyDoorPassword(roomId);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "modifyDoorPassword", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：云丁事件回调</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-03)</br>
     *
     * @return
     *
     */
    @POST
    @Path("/eventCallback")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "dding system event callback.")
    public Map<String, Object> eventCallback(
        @ApiParam(value = "ddingEventCallbackEvt", required = true) Map<String,Object> ddingEventCallbackEvt)
    {
        LOG.info("eventCallback|ddingEventCallbackEvt参数|" + ddingEventCallbackEvt);
        
        DdingEventCallbackEvt callbackEvent1 = new DdingEventCallbackEvt();
        
        callbackEvent1.setCenter_uuid(ddingEventCallbackEvt.get("center_uuid"));
        callbackEvent1.setDetail(ddingEventCallbackEvt.get("detail"));
        callbackEvent1.setElecollector_uuid(ddingEventCallbackEvt.get("elecollector_uuid"));
        callbackEvent1.setEvent(StringTools.getString(ddingEventCallbackEvt.get("event")));
        callbackEvent1.setHome_id(StringTools.getString(ddingEventCallbackEvt.get("home_id")));
        callbackEvent1.setNickname(StringTools.getString(ddingEventCallbackEvt.get("nickname")));
        callbackEvent1.setRoom_id(StringTools.getString(ddingEventCallbackEvt.get("room_id")));
        callbackEvent1.setTicket_id(StringTools.getString(ddingEventCallbackEvt.get("ticket_id")));
        callbackEvent1.setTime(ddingEventCallbackEvt.get("time"));
        callbackEvent1.setUuid(StringTools.getString(ddingEventCallbackEvt.get("uuid")));
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try
        {
            ddLockService.eventCallback(callbackEvent1);
            resultMap.put("ErrNo", DdingConstant.CALLBACK_RESPONSE_SUCCESS);
            resultMap.put("ErrMsg", StringUtils.EMPTY);
        }
        catch (LandseaException e)
        {
            // 异常在业务侧处理，此处不抛出异常
            resultMap.put("ErrNo", DdingConstant.CALLBACK_RESPONSE_FAILED);
            resultMap.put("ErrMsg", e.getErrorDesc());
        }
        
        return resultMap;
    }
    
    /**
     * 
     * [简要描述]：云丁密码操作回调</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-03)</br>
     *
     * @param callbackEvent
     * @return
     *
     */
    @POST
    @Path("/passwordEventCallback")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "dding system password event callback.")
    public Map<String, Object> passwordEventCallback(
        @ApiParam(value = "ddingPwdCallbackEvt", required = true) Map<String,Object> callbackEvent)
    {
        LOG.info("passwordEventCallback|" + callbackEvent);
        
        DdingPwdCallbackEvt callbackEvent1 = new DdingPwdCallbackEvt();
        callbackEvent1.setResult(callbackEvent.get("result"));
        callbackEvent1.setService(StringTools.getString(callbackEvent.get("service")));
        callbackEvent1.setServiceid(StringTools.getString(callbackEvent.get("serviceid")));
        callbackEvent1.setUuid(StringTools.getString(callbackEvent.get("uuid")));
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try
        {
            ddLockService.passwordEventCallback(callbackEvent1);
            resultMap.put("ErrNo", DdingConstant.CALLBACK_RESPONSE_SUCCESS);
            resultMap.put("ErrMsg", StringUtils.EMPTY);
        }
        catch (LandseaException e)
        {
            // 异常在业务侧处理，此处不抛出异常
            resultMap.put("ErrNo", DdingConstant.CALLBACK_RESPONSE_FAILED);
            resultMap.put("ErrMsg", e.getErrorDesc());
        }
        
        return resultMap;
    }
    
    /**
     * 
     * [简要描述]：获取云丁修改门锁密码日志</br>
     * [详细描述]：只查询出5条记录</br>
     * [作者]：Aaron(2017-07-05)</br>
     *
     * @param roomId 房间编号
     * @return 结果
     *
     */
    @POST
    @Path("/getModifyPwdLog")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "get modify dding lock password logs.")
    public Response getModifyPwdLog(@ApiParam(value = "roomId", required = true) Integer roomId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            List<DdingModPwdLog> result = ddLockService.getModifyPwdLog(roomId);
            map.setData(result);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "getModifyPwdLog", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    @POST
    @Path("/getRoomPwdEffectiveTime")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "获取房间门锁密码有效期.")
    public Response getRoomPwdEffectiveTime(@ApiParam(value = "roomId", required = true) Integer roomId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            String result = ddLockService.getRoomPwdEffectiveTime(roomId);
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("time", result);
            map.setData(resultMap);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "getRoomPwdEffectiveTime", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：检查项目是否配置云丁锁</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-05)</br>
     *
     * @param paramMap 房间编号
     * @return 结果
     *
     */
    @POST
    @Path("/checkProjectConfig")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "检查项目是否配置云丁锁")
    public Response checkProjectConfig(@ApiParam(value = "paramMap", required = true) Map<String, Object> paramMap)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            Integer projectId = (Integer)paramMap.get("projectId");
            Map<String, Object> result = ddLockService.checkProjectConfigExists(projectId);
            map.setData(result);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "checkProjectConfig", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    @POST
    @Path("/sendAddPwdByRoom")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "按房间实际房租新增密码,多个房间ID逗号分割")
    public Response sendAddPwdByRoom(@ApiParam(value = "param", required = true) SendAddPwdByRoomReq req)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            List<String> list = sendByRoomService.sendAddPwds(req);
            map.setData(list);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "sendAddPwdByRoom", e, map);
        }
        catch (Exception e)
        {
            LOG.error("下发失败.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @POST
    @Path("/updateSynRoomByPrjId")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "增量修改部分失败的项目房间")
    public Response updateSynRoomByPrjId(@ApiParam(value = "prjId", required = true) Integer prjId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            ddLockService.updateSynRoomByPrjId(prjId);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOG, "updateSynRoomByPrjId", e, map);
        }
        catch (Exception e)
        {
            LOG.error("下发失败.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
}
